package com.ycsj.goldmedalnewconcept.teacher.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ycsj.common.base.BaseLazyFragment;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.manager.PickerManager;
import com.ycsj.common.manager.SrfManager;
import com.ycsj.common.utils.DateUtils;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.teacher.activity.TeacherAttendanceDetailsActivity;
import com.ycsj.goldmedalnewconcept.teacher.adapter.StudentAnalyRvAdapter;
import com.ycsj.goldmedalnewconcept.teacher.bean.StudentAnalyInfo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 学生分析
 * Created by Administrator on 2018/7/2 0002.
 */

public class TeacherStudentAnalyFragment extends BaseLazyFragment implements StudentAnalyRvAdapter.onDetailsClickListener {

    //下拉刷新
    @BindView(R.id.srf)
    SmartRefreshLayout srf;

    //列表控件
    @BindView(R.id.rv)
    RecyclerView rv;

    //加载视图
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;

    //内容布局
    @BindView(R.id.ll_content)
    LinearLayout llContent;

    //开始时间
    @BindView(R.id.tv_begin_time)
    TextView tvBeginTime;

    //结束时间
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;

    //数据集合
    private List<StudentAnalyInfo.DataBean> oldDatas;

    //适配器
    private StudentAnalyRvAdapter adapter;

    //空视图
    private View emptyView;

    //班级号
    private String classNum;

    //头布局
    private View headView;

    //选择的开始时间和结束
    private String begindate, enddate;

    //请求的参数
    private String acc, role, apptoken;

    public static final String TAG = TeacherStudentAnalyFragment.class.getName();

    //单体模式
    private static class LazyHolder {
        private static final TeacherStudentAnalyFragment INSTANCE = new TeacherStudentAnalyFragment();
    }

    public static final TeacherStudentAnalyFragment newInstance(String classNum) {
        TeacherStudentAnalyFragment teacherStudentAnalyFragment = TeacherStudentAnalyFragment.LazyHolder.INSTANCE;
        Bundle bundle = new Bundle();
        bundle.putString("classnum", classNum);
        teacherStudentAnalyFragment.setArguments(bundle);
        return teacherStudentAnalyFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.teacher_fragment_student_analy;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

        //初始化视图
        initState();

        //获取班级号
        initIntent();

        //初始化下拉刷新控件
        initSrf();

        //计算初次进入的默认日期
        initTime();

        //初始化列表控件
        initRv();

        //初始化请求参数
        initParams();

        //请求服务器
        http(BqaManager.NORML);
    }


    /**
     * 初始化请求参数
     */
    private void initParams() {
        acc = AccountUtils.getAccount(getContext());
        role = AccountUtils.getRole(getContext());
        apptoken = AccountUtils.getToken(getContext());
    }


    /**
     * 初始化视图
     */
    private void initState() {
        rlLoading.setVisibility(View.VISIBLE);
    }

    /**
     * 获取班级号
     */
    private void initIntent() {
        classNum = getArguments().getString("classnum");
    }


    /**
     * 初始化开始时间和结束时间.默认开始时间为当前月份的前一个
     */
    private void initTime() {
        enddate = DateUtils.getTime(new Date(), "yyyy-MM-dd");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
        begindate = format.format(m);

        //设置初始时间
        tvBeginTime.setText(DateUtils.getFmTime(begindate));
        tvEndTime.setText(DateUtils.getFmTime(enddate));
    }


    /**
     * 初始化下拉刷新控件
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, null);
    }

    /**
     * 初始化列表控件
     */
    private void initRv() {
        headView = View.inflate(getContext(), R.layout.teacher_headview_analy, null);
        oldDatas = new ArrayList<>();
        emptyView = View.inflate(getContext(), R.layout.base_rv_common_empty_view, null);
        TextView tvMsg = emptyView.findViewById(R.id.tv_content);
        tvMsg.setText("暂无数据");
        adapter = new StudentAnalyRvAdapter(getContext(), R.layout.teacher_rv_student_analy, oldDatas);
        adapter.setListener(this);
        adapter.addHeaderView(headView);
    }

    /**
     * @param pos
     */
    private void showTimePicker(final int pos) {
        PickerManager.showPickerByYeaerAndMonthAndDayByLimit(getContext(), new PickerManager.onSelectedListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (pos == 0) {

                    String chooseBeginDate = DateUtils.getTime(date, "yyyy-MM-dd");

                    //比较时间差,然后刷新页面数据
                    long end = DateUtils.getTime(enddate, "yyyy-MM-dd");
                    long start = DateUtils.getTime(chooseBeginDate, "yyyy-MM-dd");

                    //计算选择的开始和结束时间,转化为date格式
                    Date startDate = null;
                    Date endDate = null;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                    try {
                        startDate = sdf.parse(chooseBeginDate);
                        endDate = sdf.parse(enddate);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    if (end <= start) {
                        ToastUtils.showShort("选择的开始时间不能大于结束时间");
                        return;
                    } else if (DateUtils.getDiffMonth(startDate, endDate) < 1) {
                        //小于1个月
                        ToastUtils.showShort("选择的时间间隔不能小于1个月");
                        return;
                    } else if (DateUtils.getDiffMonth(startDate, endDate) > 6) {
                        //大于6个月
                        ToastUtils.showShort("选择的时间间隔不能超过6个月");
                        return;
                    } else {

                        begindate = DateUtils.getTime(date, "yyyy-MM-dd");

                        tvBeginTime.setText(DateUtils.getFmTime(begindate));

                        //刷新数据
                        http(BqaManager.PULLREFRESH);
                    }
                } else if (pos == 1) {

                    String chooseEndDate = DateUtils.getTime(date, "yyyy-MM-dd");

                    //比较时间差,然后刷新页面数据
                    long end = DateUtils.getTime(chooseEndDate, "yyyy-MM-dd");
                    long start = DateUtils.getTime(begindate, "yyyy-MM-dd");

                    //计算选择的开始和结束时间,转化为date格式
                    Date startDate = null;
                    Date endDate = null;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                    try {
                        startDate = sdf.parse(begindate);
                        endDate = sdf.parse(chooseEndDate);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    if (end <= start) {
                        ToastUtils.showShort("选择的结束时间不能小于开始时间");
                    } else if (DateUtils.getDiffMonth(startDate, endDate) < 1) {
                        //小于1个月
                        ToastUtils.showShort("选择的时间间隔不能小于1个月");
                        return;
                    } else if (DateUtils.getDiffMonth(startDate, endDate) > 6) {
                        //大于6个月
                        ToastUtils.showShort("选择的时间间隔不能超过6个月");
                        return;
                    } else {
                        enddate = DateUtils.getTime(date, "yyyy-MM-dd");
                        tvEndTime.setText(DateUtils.getFmTime(enddate));
                        //刷新数据
                        http(BqaManager.PULLREFRESH);
                    }
                }

            }
        });
    }

    /**
     * 请求服务器获取数据
     *
     * @param method
     */
    private void http(final int method) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "7");
        map.put("acc", acc);
        map.put("role", role);
        map.put("classnum", classNum);
        map.put("begindate", begindate);
        map.put("enddate", enddate);
        map.put("apptoken", apptoken);
        map.put("platform", "2");

        HttpUtils.post(HttpAddress.STUDENTANALY, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                BqaManager.setErrorNet(rlLoading, srf, method, adapter);
            }

            @Override
            public void onResponse(String response, int id) {
                if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                    rlLoading.setVisibility(View.GONE);
                }
                if (llContent != null && llContent.getVisibility() != View.VISIBLE) {
                    llContent.setVisibility(View.VISIBLE);
                }

                if (!TextUtils.isEmpty(response)) {
                    StudentAnalyInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, StudentAnalyInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }

                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            List<StudentAnalyInfo.DataBean> newDatas = info.getData();
                            if (newDatas != null) {
                                if (method == BqaManager.NORML) {
                                    oldDatas.clear();
                                    oldDatas.addAll(newDatas);
                                    BqaManager.setRv(emptyView, getContext(), adapter, rv);
                                } else {
                                    //更新数据
                                    BqaManager.updateRvBySmf(method, srf, rv, oldDatas, newDatas, adapter);
                                    adapter.setEnableLoadMore(false);
                                }
                            }

                        } else {
                            ToastUtils.showShort(Constants.ERRORSTATE + info.getState());
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.ERROR);
                }
            }
        });
    }


    /**
     * 点击详情的点击事件
     *
     * @param item
     */
    @Override
    public void onDetailsClick(StudentAnalyInfo.DataBean item) {
        Intent intent = new Intent(getContext(), TeacherAttendanceDetailsActivity.class);
        intent.putExtra("data", item);
        intent.putExtra("begindate", begindate);
        intent.putExtra("enddate", enddate);
        startActivity(intent);
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @OnClick({R.id.tv_begin_time, R.id.tv_end_time})
    public void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.tv_begin_time:
                showTimePicker(0);
                break;
            case R.id.tv_end_time:
                showTimePicker(1);
                break;
        }

    }

}
